package com.wcl.hencodertest.test06_drawing;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ConvertUtils;
import com.wcl.hencodertest.R;

/**
 * @项目名： HenCoderTest
 * @包名： com.wcl.hencodertest.test06_drawing
 * @文件名: AvatarView
 * @创建者: kilin
 * @创建时间: 2020/4/15 20:42
 * @描述： 学习Xfermode
 */
public class AvatarView extends View {

    public static final int RADIUS = ConvertUtils.dp2px(100);
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);

    public AvatarView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawCircle(getWidth() / 2, getHeight() / 2, RADIUS + 10, paint);//边线

        int saved = canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG);//离屏缓冲


        canvas.drawCircle(getWidth() / 2, getHeight() / 2, RADIUS, paint);
        paint.setXfermode(xfermode);
        canvas.drawBitmap(getAvatar(RADIUS * 2), getWidth() / 2 - RADIUS, getHeight() / 2 - RADIUS, paint);
        paint.setXfermode(null);

        canvas.restoreToCount(saved);//离屏缓冲恢复
    }

    Bitmap getAvatar(int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(), R.drawable.pic, options);
        options.inJustDecodeBounds = false;
        options.inDensity = options.outWidth;
        options.inTargetDensity = width;
        return BitmapFactory.decodeResource(getResources(), R.drawable.pic, options);
    }
}
